import React, { Component } from "react";
import axios from "axios";
import {
  List,
  InputItem,
  WhiteSpace,
  Button,
  Toast,
  WingBlank
} from "antd-mobile";
import formWrapper from "../../components/formWrapper";
import Validator from '../../validator'

@formWrapper
class Register extends Component {
  constructor(props) {
    super(props);
    this.handleRegister = this.handleRegister.bind(this);
  }
  handleRegister() {
    let { pwd, user } = this.props.state;


    function validataFun() {
      var validator = new Validator();
      validator.add(user,[{strategy:'isNonEmpty',errorMsg:'用户名不能为空'}]);
      validator.add(pwd, [
        { strategy: "isNonEmpty", errorMsg: "密码不能为空" },
        { strategy: "minLength:6", errorMsg: "密码长度不能小于6位" },
      ]);
      var errorMsg = validator.start();
      return errorMsg;
    }
    let errorMsg = validataFun();
    if (errorMsg) {
      Toast.info(errorMsg);
      return;
    }

    axios.post("/api/user/register", { pwd, user }).then(res => {
      Toast.info(res.data.msg);
      if (res.data.success) {
        this.props.history.push("/");
      }
    });
  }
  render() {
    return (
      <WingBlank>
        <List>
          <InputItem onChange={v => this.props.handleChange("user", v)}>
            用户名
          </InputItem>
          <InputItem
            type="password"
            onChange={v => this.props.handleChange("pwd", v)}
          >
            密码
          </InputItem>
          <WhiteSpace />
          <Button type="primary" onClick={this.handleRegister}>
            注册
          </Button>
          <WhiteSpace />
          <Button
            type="primary"
            onClick={() => this.props.history.push("/login")}
          >
            登陆
          </Button>
        </List>
      </WingBlank>
    );
  }
}

export default Register;
